'use client';

import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import diff from 'microdiff';
import type { IConfigPost, IDifference } from '@/interfaces';
import { updatePostConfig } from '@/services/api';
import useToast from '@/hooks/useToast';
import { getDiffData } from '@/lib/tool';
import Box from '@/app/[locale]/admin/common/box';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function UpdateConfigPost({
  source,
  translatedFields,
}: {
  source: IConfigPost;
  translatedFields: PrefixedTTranslatedFields<'configAdminPage'>;
}) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    enableCreateNotice?: boolean;
    enableUpdateNotice?: boolean;
    enableUpdateContentNotice?: boolean;
    enableUpdateStateNotice?: boolean;
  }>({
    enableCreateNotice: source.enableCreateNotice,
    enableUpdateNotice: source.enableUpdateNotice,
    enableUpdateContentNotice: source.enableUpdateContentNotice,
    enableUpdateStateNotice: source.enableUpdateStateNotice,
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const [isDisabledSave, setIsDisabledSave] = useState(true);

  const updatePostConfigMutation = useMutation(updatePostConfig);

  useEffect(() => {
    const diffData = diff(
      {
        enableCreateNotice: source.enableCreateNotice,
        enableUpdateNotice: source.enableUpdateNotice,
        enableUpdateContentNotice: source.enableUpdateContentNotice,
        enableUpdateStateNotice: source.enableUpdateStateNotice,
      },
      form,
    );
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [form, source]);

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const data = getDiffData(differenceData);
      await updatePostConfigMutation.mutateAsync({
        data,
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.operate.updateCompleted,
      });
    } catch (e) {
      updatePostConfigMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setDifferenceData([]);
    }
  }

  function onChangeForm(e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) {
    const name = e.target.name;
    const value = e.target.value;

    if (
      [
        'enableCreateNotice',
        'enableUpdateNotice',
        'enableUpdateContentNotice',
        'enableUpdateStateNotice',
      ].includes(name)
    ) {
      setForm({ ...form, [name]: value === 'true' });
    } else {
      setForm({ ...form, [name]: value });
    }
  }

  return (
    <Box>
      <form onSubmit={onClickSave} className="vstack gap-4">
        <div>
          <label className="form-label">
            {translatedFields.config.post.enableCreateNotice}
          </label>
          <select
            name="enableCreateNotice"
            value={form.enableCreateNotice ? 'true' : 'false'}
            onChange={onChangeForm}
            className="form-select"
            aria-label="enableCreateNotice"
          >
            <option value="true">true</option>
            <option value="false">false</option>
          </select>
        </div>

        <div>
          <label className="form-label">
            {translatedFields.config.post.enableUpdateNotice}
          </label>
          <select
            name="enableUpdateNotice"
            value={form.enableUpdateNotice ? 'true' : 'false'}
            onChange={onChangeForm}
            className="form-select"
            aria-label="enableUpdateNotice"
          >
            <option value="true">true</option>
            <option value="false">false</option>
          </select>
        </div>

        <div>
          <label className="form-label">
            {translatedFields.config.post.enableUpdateContentNotice}
          </label>
          <select
            name="enableUpdateContentNotice"
            value={form.enableUpdateContentNotice ? 'true' : 'false'}
            onChange={onChangeForm}
            className="form-select"
            aria-label="enableUpdateContentNotice"
          >
            <option value="true">true</option>
            <option value="false">false</option>
          </select>
        </div>

        <div>
          <label className="form-label">
            {translatedFields.config.post.enableUpdateStateNotice}
          </label>
          <select
            name="enableUpdateStateNotice"
            value={form.enableUpdateStateNotice ? 'true' : 'false'}
            onChange={onChangeForm}
            className="form-select"
            aria-label="enableUpdateStateNotice"
          >
            <option value="true">true</option>
            <option value="false">false</option>
          </select>
        </div>

        <button
          type="submit"
          disabled={updatePostConfigMutation.isLoading || isDisabledSave}
          className="btn btn-success col col-lg-2 my-4"
        >
          {updatePostConfigMutation.isLoading && <Spinner classs="me-2" />}
          {translatedFields.operate.update}
        </button>
      </form>
    </Box>
  );
}
